package edu.gatech.cc.CFAWaffleFriesWheresMyStuff.gui;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.R;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.Datastore;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.Datastore.CanNotDeleteSelfException;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.Datastore.UserDoesNotExistException;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.Datastore.UserIsNotAdminException;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.DatastoreFactory;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.UserManager;
import edu.gatech.cc.CFAWaffleFriesWheresMyStuff.common.User;

/**
 * Displays the settings and admin actions available to the logged in user.
 * @author Matthew Barulic
 *
 */
public class SettingsActivity extends Activity {

	private User _user;
	private UserManager _userManager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_settings);
		Bundle extras = getIntent().getExtras();
		
		Datastore ds = DatastoreFactory.getDatastore(getApplicationContext());
		
		_userManager = new UserManager(ds);
		
		try {
			_user = _userManager.getUser(extras.getString("user"));
		} catch (UserDoesNotExistException e) {
			//This should never happen.
			e.printStackTrace();
		}
		
		if(_user.isAdmin())
		{
			((Button)findViewById(R.id.settings_unlock_button)).setVisibility(View.VISIBLE);
			((Button)findViewById(R.id.settings_createAdmin_button)).setVisibility(View.VISIBLE);
			((Button)findViewById(R.id.settings_delete_button)).setVisibility(View.VISIBLE);
			((TextView)findViewById(R.id.settings_title_text)).setText("Admin Settings");
		}
		
		final SettingsActivity me = this;
		
		((Button)findViewById(R.id.settings_unlock_button)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(me);
				List<String> requestResults = _userManager.getAllUsernames();
				final String[] usernames = new String[requestResults.size()];
				requestResults.toArray(usernames);
			    builder.setTitle("Pick A User")
			           .setItems(usernames, new DialogInterface.OnClickListener() {
			               public void onClick(DialogInterface dialog, int which) {
			            	   me.unlockUser(usernames[which]);
			               }
			    });
			    builder.create().show();
			}
		});
		
		((Button)findViewById(R.id.settings_delete_button)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(me);
				List<String> requestResults = _userManager.getAllUsernames();
				final String[] usernames = new String[requestResults.size()];
				requestResults.toArray(usernames);
			    builder.setTitle("Pick A User")
			           .setItems(usernames, new DialogInterface.OnClickListener() {
			               public void onClick(DialogInterface dialog, int which) {
			            	   me.deleteUser(usernames[which]);
			               }
			    });
			    builder.create().show();
			}
		});
		
		((Button)findViewById(R.id.settings_createAdmin_button)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(me);
				List<String> requestResults = _userManager.getAllUsernames();
				final String[] usernames = new String[requestResults.size()];
				requestResults.toArray(usernames);
			    builder.setTitle("Pick A User")
			           .setItems(usernames, new DialogInterface.OnClickListener() {
			               public void onClick(DialogInterface dialog, int which) {
			            	   me.turnUserToAdmin(usernames[which]);
			               }
			    });
			    builder.create().show();
			}
		});
	}

	/**
	 * Sends a signal to the UserManager to delete the given user
	 * @param username The username of the given
	 */
	private void deleteUser(String username) {
		if(_user.isAdmin())
		{
			try {
				_userManager.deleteUser(username, _user.getUsername());
			} catch (UserDoesNotExistException e) {
				// This should never happen because we selecting from the list of existing users.
			} catch (UserIsNotAdminException e) {
				// This should never happen
				e.printStackTrace();
			} catch (CanNotDeleteSelfException e) {
				// TODO Show alert for CanNotDeleteSelfException!
				e.printStackTrace();
			}
		}
	}

	/**
	 * Launches the registration activity setup to make a new admin.
	 * Does NOT end the settings activity.
	 */
	private void turnUserToAdmin(String username)
	{
		try {
			_userManager.turnUserToAdmin(username);
		} catch (UserDoesNotExistException e) {
			// This should never happen
			e.printStackTrace();
		}
	}
	
	/**
	 *	Tells _login to unlock the user with the given username.
	 * @param username The username of the user you want to unlock.
	 */
	private void unlockUser(String username)
	{
		if(_user.isAdmin())
		{
			try {
				_userManager.unlockUser(username);
			} catch (UserDoesNotExistException e) {
				// This should never happen because we selecting from the list of existing users.
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_settings, menu);
		return true;
	}

}
